#!/usr/bin/perl -w

use cm2bug;
use Getopt::Long;
use File::Basename;

$_PRG=basename($0);

sub usage {
	print "
Usage: $_PRG --table T [--dbfile D] [--outfile O]
";
	exit(1);
}

$ARG_dbfile="dbfile";
if(!GetOptions(
	"dbfile=s"	=> \$ARG_dbfile,
	"table=s"	=> \$ARG_table,
	"outfile=s"	=> \$ARG_outfile,
)) {
	usage;
}

if(!defined($ARG_table)) {
	usage;
}

$ARG_outfile="-" if !defined($ARG_outfile);
if($ARG_outfile ne "-" && -f $ARG_outfile) {
	print STDERR "Error: Specified file to generate already exists!\n";
	exit 1;
}

#########################################################################
# Open the database, prepare and execute the statement, ready for 	#
# writing records.							#
#########################################################################

$DBH = cm2bug->new($ARG_dbfile);

if(!defined($DBH)) {
	print STDERR "Error: Unable to open dataase $ARG_dbfile!\n";
	exit 1;
}

if(!$DBH->exists("table",$ARG_table)) {
	print STDERR "Error: Table \"$ARG_table\" does not exist.\n";
	exit 1;
}

$schema=$DBH->get_object_schema("table",$ARG_table);
if(!defined($schema)) {
	($cc,$rc)=$DBH->error;
	print STDERR "Error: $rc\n";
	exit 1;
}

if(!open($fd,">$ARG_outfile")) {
	print STDERR "Unable to open '$ARG_outfile' for writing:\n$!\n";
	exit 1;
}

$i=0;
if(!print $fd "SCHEMA::=",unpack("H*",$schema),"\n") {
	print STDERR "Error attempting to write to output - aborting!\n";
	exit 1;
}

$aref=$DBH->get_rows("SELECT * FROM $ARG_table");
if(!defined($aref)) {
	($cc,$rc)=$DBH->error;
	print STDERR "Error: $rc\n";
	exit 1;
}

foreach $aa (@$aref) {
	@R=();
	foreach (sort(keys %$aa)) {
		next if !defined($aa->{$_});
		next if $aa->{$_} eq "";
		push @R,"$_:".unpack("H*",$aa->{$_});
	}
	if(!print $fd join(",",@R),"\n") {
		print STDERR "Error attempting to write to output - aborting!\n";
		exit 1;
	}
	$i++;
}
close($fd);
print STDERR "$i Record",$i==1 ? "" : "s"," dumped.\n";

exit(0);
